<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试SSE连接</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            background: #f5f5f5;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .success { background: #d4edda; color: #155724; }
        .error { background: #f8d7da; color: #721c24; }
        .info { background: #d1ecf1; color: #0c5460; }
        .log {
            background: #000;
            color: #0f0;
            padding: 10px;
            border-radius: 4px;
            height: 300px;
            overflow-y: auto;
            font-family: monospace;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover { background: #0056b3; }
        button:disabled { background: #6c757d; cursor: not-allowed; }
        input[type="file"] { margin: 10px 0; }
    </style>
</head>
<body>
    <h1>测试SSE连接</h1>
    
    <div class="container">
        <h3>1. 上传视频文件</h3>
        <input type="file" id="videoFile" accept="video/*">
        <button onclick="startRealtimeProcessing()" id="startBtn">开始实时处理</button>
        <button onclick="stopRealtimeProcessing()" id="stopBtn" disabled>停止处理</button>
    </div>
    
    <div class="container">
        <h3>2. 连接状态</h3>
        <div id="status" class="status info">等待开始...</div>
    </div>
    
    <div class="container">
        <h3>3. 实时数据显示</h3>
        <div id="imageContainer" style="text-align: center; margin: 20px 0;">
            <img id="realtimeImage" style="max-width: 100%; max-height: 400px; display: none;">
            <div id="noImage">等待视频数据...</div>
        </div>
        <div id="frameInfo" class="status info">帧数: 0 | 检测人数: 0</div>
    </div>
    
    <div class="container">
        <h3>4. 日志</h3>
        <div id="log" class="log"></div>
        <button onclick="clearLog()">清空日志</button>
    </div>

    <script>
        let eventSource = null;
        let isProcessing = false;

        function log(message) {
            const logDiv = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            logDiv.innerHTML += `[${timestamp}] ${message}\n`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }

        function updateStatus(message, type = 'info') {
            const statusDiv = document.getElementById('status');
            statusDiv.textContent = message;
            statusDiv.className = `status ${type}`;
        }

        function clearLog() {
            document.getElementById('log').innerHTML = '';
        }

        async function startRealtimeProcessing() {
            const fileInput = document.getElementById('videoFile');
            const file = fileInput.files[0];
            
            if (!file) {
                alert('请先选择视频文件');
                return;
            }

            try {
                updateStatus('正在启动实时处理...', 'info');
                log('开始上传视频文件...');

                const formData = new FormData();
                formData.append('file', file);
                formData.append('conf', '0.5');
                formData.append('iou', '0.7');

                const response = await fetch('http://localhost:5000/api/pose/realtime/start', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                
                if (result.success) {
                    updateStatus('实时处理启动成功，正在连接SSE...', 'success');
                    log('实时处理启动成功: ' + JSON.stringify(result));
                    
                    // 等待一下让后端开始处理
                    setTimeout(() => {
                        connectSSE();
                    }, 1000);
                } else {
                    throw new Error(result.error || '启动失败');
                }
            } catch (error) {
                updateStatus('启动失败: ' + error.message, 'error');
                log('启动失败: ' + error.message);
            }
        }

        function connectSSE() {
            if (eventSource) {
                eventSource.close();
            }

            log('正在连接SSE流...');
            updateStatus('正在连接SSE流...', 'info');

            eventSource = new EventSource('http://localhost:5000/api/pose/realtime/stream');

            eventSource.onopen = function(event) {
                updateStatus('SSE连接已建立', 'success');
                log('✅ SSE连接已建立');
                isProcessing = true;
                document.getElementById('startBtn').disabled = true;
                document.getElementById('stopBtn').disabled = false;
            };

            eventSource.onmessage = function(event) {
                try {
                    const data = JSON.parse(event.data);
                    log('收到数据: ' + JSON.stringify(data));
                    
                    if (data.error) {
                        updateStatus('服务器错误: ' + data.error, 'error');
                        log('❌ 服务器错误: ' + data.error);
                    } else if (data.image) {
                        // 显示图像
                        const img = document.getElementById('realtimeImage');
                        const noImg = document.getElementById('noImage');
                        img.src = 'data:image/jpeg;base64,' + data.image;
                        img.style.display = 'block';
                        noImg.style.display = 'none';
                        
                        // 更新帧信息
                        const frameInfo = document.getElementById('frameInfo');
                        frameInfo.textContent = `帧数: ${data.frame || 0} | 检测人数: ${data.detections ? data.detections.length : 0}`;
                        
                        log(`✅ 显示帧 ${data.frame}, 检测到 ${data.detections ? data.detections.length : 0} 人`);
                    }
                } catch (e) {
                    log('❌ 解析数据失败: ' + e.message);
                }
            };

            eventSource.onerror = function(event) {
                updateStatus('SSE连接错误', 'error');
                log('❌ SSE连接错误: ' + event);
                
                if (eventSource.readyState === EventSource.CLOSED) {
                    log('连接已关闭');
                } else if (eventSource.readyState === EventSource.CONNECTING) {
                    log('正在重新连接...');
                }
            };
        }

        async function stopRealtimeProcessing() {
            try {
                updateStatus('正在停止处理...', 'info');
                log('正在停止处理...');

                const response = await fetch('http://localhost:5000/api/pose/realtime/stop', {
                    method: 'POST'
                });

                const result = await response.json();
                
                if (result.success) {
                    updateStatus('处理已停止', 'success');
                    log('✅ 处理已停止');
                } else {
                    throw new Error(result.error || '停止失败');
                }
            } catch (error) {
                updateStatus('停止失败: ' + error.message, 'error');
                log('❌ 停止失败: ' + error.message);
            } finally {
                if (eventSource) {
                    eventSource.close();
                    eventSource = null;
                }
                isProcessing = false;
                document.getElementById('startBtn').disabled = false;
                document.getElementById('stopBtn').disabled = true;
            }
        }

        // 页面加载时检查服务器状态
        window.onload = async function() {
            try {
                const response = await fetch('http://localhost:5000/api/pose/status');
                const result = await response.json();
                updateStatus('服务器状态正常', 'success');
                log('✅ 服务器状态: ' + JSON.stringify(result));
            } catch (error) {
                updateStatus('无法连接到服务器', 'error');
                log('❌ 无法连接到服务器: ' + error.message);
            }
        };
    </script>
</body>
</html>

